package com.whenjun.interceptor;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @ClassName: TackledServletRequestWrapper.java
 * @Description: 
 *
 * @version: v1.0.0
 * @author: wanwenjun
 * @date: 2019年3月6日 下午2:22:19
 */
public class TackledServletRequestWrapper extends HttpServletRequestWrapper {

	private HttpServletRequest request;
	private InputStream inputStream;
	
	public TackledServletRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		this.request = request;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {

		if (request.getAttribute("POST-DATA") == null)
			return request.getInputStream();
		inputStream = IOUtils.toInputStream(request.getAttribute("POST-DATA").toString(),"UTF-8");
		return new ServletInputStream() {
			@Override
			public int read() throws IOException {
				int i = inputStream.read();
				return i;
			}

			@Override
			public boolean isFinished() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean isReady() {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void setReadListener(ReadListener listener) {
				// TODO Auto-generated method stub
				
			}
		};
	}

}